<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
class Api_Model_UserLocationMapper {
	protected $_db_table;

	public function __construct() {
		$this->_db_table = new Api_Model_DbTable_UserLocation();
	}

	public function postUserLocation($userlocation, $user_tour_id) {
		$db_table = new Api_Model_DbTable_UserLocation();
		if($userlocation != "") {
			$affectedRow = $db_table->insert($userlocation);

			if ($affectedRow){

				date_default_timezone_set('Asia/Ho_Chi_Minh');
				$currentDateTime = date('Y-m-d H-i-s');
				$this->_db_table->update(array('send_time' => $currentDateTime),
				array('user_tour_id = ?' => $user_tour_id));


			} else {
				throw new Exception('Internal Server Error' ,500);
			}

		} else{
			throw new Exception(json_encode(array('meta' => 'Bad request')),400);
		}
	}

	public function getUserLocation($user_tour_id) {
		$select = $this->_db_table->select()->from('user_location', array('*'))->where('user_tour_id = ?', $user_tour_id);;

		$result = $this->_db_table->fetchAll($select);

		if(count($result) == 0) {
			throw new Exception(json_encode(array('meta' => 'Not found')),404);
		} else {
			foreach ($result as $row) {
				// $row should be a Zend_Db_Table_Row object
				// cast to array
				$rowArray = $row->toArray();

				$json[] = array('user_location' => $rowArray);

			}
			return $json;
		}
	}

	public function getuserid($token){

		$db_table = new Api_Model_DbTable_User();

		$select = $db_table->select()->from('users', array('*'))->where('md5(CONCAT(md5(username),md5(password))) = ?', $token);
		$result = $db_table->fetchAll($select);

		if (count($result) != 0){
			$row = $result->current();
			$user_object = new Api_Model_User($row);

			$user = array(
                'user_id' => $user_object->user_id,
                'name' => $user_object->name,
                'dob' => $user_object->dob,
                'sex' => $user_object->sex,
                'address' => $user_object->address,
                'email' => $user_object->email,
                'phone' => $user_object->phone,
                'avatar_link' => $user_object->avatar_link,
                'last_login' => $user_object->last_login
			);
			return $user;
		} else {
			throw new Exception('Unauthorized', 401);
		}
	}

}
